Skip to content

Fix: DocumentEditor open delay by deferring content load#477

Open
urjitc wants to merge 6 commits intomainfrom
capy/defer-editor-content-load
Open

Fix: DocumentEditor open delay by deferring content load#477
urjitc wants to merge 6 commits intomainfrom
capy/defer-editor-content-load

Conversation

@urjitc
Copy link
Copy Markdown
Member

@urjitc urjitc commented Apr 28, 2026

Defer initial content load in DocumentEditor to avoid blocking the modal's open animation with synchronous markdown parsing and KaTeX rendering.

  • Remove content / contentType from useEditor initial options so the editor mounts empty and paints immediately.
  • Use double requestAnimationFrame for the first content load to ensure it runs after the modal's open paint.
  • Subsequent prop changes (e.g., ZeroDB sync) apply synchronously for instant feedback.
  • Re-apply autofocus after deferred initial load to focus at end of content.

Open ENG-074 ENG-074

Summary by CodeRabbit

  • Performance

    • Deferred initial editor synchronization to improve visual responsiveness during load and modal rendering.
    • Subsequent external content updates now apply immediately for a smoother editing experience.
  • Bug Fixes

    • Autofocus reliably places the cursor at the end after initial content loads.
    • Prevents unnecessary content overwrites and cancels pending updates when the editor changes.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Apr 28, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
thinkex Ready Ready Preview, Comment Apr 29, 2026 4:55am

Request Review

@urjitc urjitc added the capy Generated by capy.ai label Apr 28, 2026 — with Capy AI
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 28, 2026

Warning

Rate limit exceeded

@capy-ai[bot] has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 30 minutes and 10 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a4eae1d1-95be-4e8c-9716-74457c742b1f

📥 Commits

Reviewing files that changed from the base of the PR and between 57168ce and b008639.

📒 Files selected for processing (1)
  • src/components/editor/DocumentEditor.tsx
📝 Walkthrough

Walkthrough

Initial content initialization was removed from useEditor; content syncing moved to an effect that defers the first content application using two chained requestAnimationFrame calls, skips redundant writes by comparing live editor state, applies subsequent updates immediately, resets a load flag when the editor changes, and cancels scheduled frames on cleanup.

Changes

Cohort / File(s) Summary
Editor Content Synchronization
src/components/editor/DocumentEditor.tsx
Removed content from useEditor init. Added hasLoadedInitialContentRef reset on editor changes. Moved content application into an effect that defers the first write with two requestAnimationFrame calls, compares incoming content against current editor state to avoid redundant edits, applies later updates immediately, handles autofocus positioning, and cancels scheduled rAFs on cleanup.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 Hopped through frames to time the paste,
Two rAFs later, content finds its place.
Checks for duplicates, skips the repeat,
Focuses softly when load feels complete.
Tiny rabbit, tidy sync — neat!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and specifically describes the main change: deferring content load to fix DocumentEditor open delay, which is the core objective of the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch capy/defer-editor-content-load

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 30 minutes and 10 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

Requires human review: Modifying the initialization lifecycle and content synchronization of the core DocumentEditor is a high-impact logic change that requires human review.

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented Apr 28, 2026

Greptile Summary

This PR optimises DocumentEditor by deferring the initial content load (markdown parsing + KaTeX rendering) until after the modal's open animation by omitting content/contentType from useEditor and scheduling a double requestAnimationFrame in the sync effect. Subsequent prop updates (ZeroDB sync) are applied synchronously via a hasLoadedInitialContentRef flag, and autofocus is re-applied after the deferred load.

Confidence Score: 4/5

Safe to merge with minor style/robustness improvements

No P0/P1 bugs found. Two P2 findings: autofocus being unnecessarily included in the dependency array (causes spurious applyContent calls after initial load) and the hasLoadedInitialContentRef not being reset when the editor instance is recreated. Core animation-deferral logic and rAF cancellation are correct.

src/components/editor/DocumentEditor.tsx — review the effect dependency array and ref reset behaviour

Important Files Changed

Filename Overview
src/components/editor/DocumentEditor.tsx Defers initial content load via double rAF to avoid blocking modal-open animation; two P2 style/robustness issues found (unnecessary autofocus dependency and stale hasLoadedInitialContentRef on editor recreation).

Fix All in Cursor

Reviews (1): Last reviewed commit: "Defer DocumentEditor content load to fix..." | Re-trigger Greptile

if (rafA != null) cancelAnimationFrame(rafA);
if (rafB != null) cancelAnimationFrame(rafB);
};
}, [editor, content, contentType, autofocus]);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 autofocus in deps triggers unnecessary applyContent after initial load

autofocus is only consumed in the initial-load rAF branch. Once hasLoadedInitialContentRef.current is true, any change to autofocus re-runs the effect and calls applyContent() — which, for large documents, runs a full JSON.stringify comparison — but never actually re-focuses the editor. Consider reading autofocus through a ref so it can be omitted from the dependency array:

const autofocusRef = useRef(autofocus);
useEffect(() => { autofocusRef.current = autofocus; }, [autofocus]);

// then in the rAF callback:
if (autofocusRef.current) { editor.commands.focus("end"); }

This eliminates spurious applyContent calls while keeping the focus behaviour correct.

Fix in Cursor

Comment on lines +957 to +961
if (hasLoadedInitialContentRef.current) {
// External update (e.g., ZeroDB sync from another tab). Apply immediately.
applyContent();
return;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 hasLoadedInitialContentRef not reset on editor recreation

hasLoadedInitialContentRef is a component-scoped useRef and persists for the lifetime of the component instance. If TipTap's useEditor ever recreates the editor object (e.g. because an extension config prop changes), the effect runs with hasLoadedInitialContentRef.current === true and applies content synchronously on the fresh editor. In most cases this is harmless, but it also means the deferred-paint optimisation is silently bypassed for any editor rebuild. Adding a reset when editor changes would make the behaviour explicit:

useEffect(() => {
  hasLoadedInitialContentRef.current = false;
}, [editor]);

Fix in Cursor

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Requires human review: Modifies the initialization and synchronization timing of a core UI component (DocumentEditor), which requires manual verification to ensure no UI flickering or race conditions.

The explicit editor.commands.focus("end") call was overriding Tiptap's
native autofocus behavior. Per Tiptap's resolveFocusPosition, autofocus:
true means "start" of doc — so the original (pre-defer) code placed the
cursor at start. Tiptap natively focuses the empty doc at position 0
via setTimeout(0) from mount(); after deferred setContent replaces the
doc, the cursor maps to position 0 of the new doc which is the start.
No explicit focus call needed.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Requires human review: This modifies the initialization lifecycle and timing of a core component. Deferring content load via animation frames can introduce race conditions and requires human review.

The Mathematics extension's NodeView calls katex.render() synchronously
every time a math node mounts, with no memoization. Reopening the same
doc (or rendering duplicate expressions across docs) repays the full
parse + DOM-build cost.

Add a CachedMathematics drop-in replacement that wraps BlockMath and
InlineMath with NodeViews backed by a module-scoped LRU cache around
katex.renderToString. Cache key = `${latex}\0${JSON.stringify(opts)}`,
shared across all editor instances. Memory cost ~75KB at the 500-entry
cap. Visual output, classes, dataset attrs, and click handling are
identical to upstream.

Caveat: assumes katexOptions.macros is not used (\gdef would mutate the
shared macros object across renders). Documented in the file.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Requires human review: This PR modifies the core initialization lifecycle of the DocumentEditor and introduces a custom caching extension for KaTeX, which requires human verification of potential side effects.

setContent uses tr.replaceWith over the full doc range, and
ProseMirror's selection mapping for a position inside a fully-replaced
range biases to the END of the replacement. So even though Tiptap's
native autofocus runs on the empty doc and lands at position 0, the
later setContent shifts the cursor to the doc end.

Explicitly call focus("start") (or setTextSelection(0) when autofocus
is false) after applyContent in the initial-load rAF to match the
original autofocus:true semantics — cursor at start, optionally
focused.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/components/editor/DocumentEditor.tsx">

<violation number="1" location="src/components/editor/DocumentEditor.tsx:985">
P2: Autofocus restores the cursor to the start instead of the end after deferred initial content load.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

// ProseMirror's selection mapping land at the END of the replacement.
// Move the cursor to the start to match Tiptap's native autofocus:true.
if (autofocusRef.current) {
editor.commands.focus("start");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Autofocus restores the cursor to the start instead of the end after deferred initial content load.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/components/editor/DocumentEditor.tsx, line 985:

<comment>Autofocus restores the cursor to the start instead of the end after deferred initial content load.</comment>

<file context>
@@ -976,6 +978,14 @@ export function DocumentEditor({
+        // ProseMirror's selection mapping land at the END of the replacement.
+        // Move the cursor to the start to match Tiptap's native autofocus:true.
+        if (autofocusRef.current) {
+          editor.commands.focus("start");
+        } else {
+          editor.commands.setTextSelection(0);
</file context>

Removing the CachedMathematics wrapper. The rAF-deferred setContent in
DocumentEditor already solves the original "dialog feels delayed on open"
complaint by unblocking the modal-open animation.

The cache only helps repeat opens / cross-doc duplicate expressions,
which is a marginal win for typical usage, and costs a custom NodeView
that has to stay in sync with upstream BlockMath/InlineMath plus a
footgun for future katexOptions.macros usage. Easier to add back later
if perf telemetry actually justifies it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

capy Generated by capy.ai

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

1 participant